package fda.hash;

import java.util.List;

import fda.base.Block;
import fda.base.Constants;
import fda.base.DiskFile2;

public class Hash {
	private int hash;			// the hash function
	private Bucket[] buckets;	// the first buckets which are pointed by the hash function
	
	public Hash() {
		// get the hashing number for modulo
		hash = Constants.MAX_TYPLES_IN_BLOCK;
		
		// create the buckets
		buckets = new Bucket[hash];
	}
	
	public void BuildHashTable(List<DiskFile2> bucketList, List<Block> blocks) {
		// get the blocks
		for(int i = 0; i < blocks.size(); i++) {
			// get the records in each block
			for(int r = 0; r < blocks.get(i).getBlockSize(); r++) {
				// calculate the records position in the hash table
				int index = (int) (blocks.get(i).getRecord(r).getKeyValue() % hash);
				// if bucket was not used yet
				if(buckets[index] == null) {
					buckets[index] = new Bucket();
				}
				// add record to the corresponding bucket
				if(buckets[index].AddRecord(blocks.get(i).getRecord(r), index)) {
					// if the bucket is full write it to the disk
					bucketList.get(index).appendTuples(buckets[index].getTuplesInBucket());
					// clear the bucket
					buckets[index] = null;
				}
			}
		}
	}
	
	// clear tailings from buckets
	public void clearTailings(List<DiskFile2> bucketList) {
		for(int i = 0; i < hash; i++) {
			if(buckets[i] != null) {
				bucketList.get(i).appendTuples(buckets[i].getTuplesInBucket());
			}
		}
	}
	
	public String getBucket(int ID) {
		return Integer.toString(ID % hash);
	}
	
	public int getHash(){
		return hash;
	}
}
